package initialize

import (
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"mxshop-api/userop-web/global"
	"mxshop-api/userop-web/proto"
	_ "mxshop-api/userop-web/utils/grpc-consul-resolver" // It's important
)

func InitSrvConn() {
	consulInfo := global.ServerConfig.ConsulInfo
	useropConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s&token=9bed74e4-1748-b21f-e871-2fca2dfabc5e", consulInfo.Host, consulInfo.Port, global.ServerConfig.UserOpSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 轮询访问
	)
	if err != nil {
		zap.S().Fatalf("[userop-web] 连接 【订单服务】 失败")
	}
	global.UserFavSrvClient = proto.NewUserFavClient(useropConn)
	global.AddressSrvClient = proto.NewAddressClient(useropConn)
	global.MessageSrvClient = proto.NewMessageClient(useropConn)

	goodsConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s&token=9bed74e4-1748-b21f-e871-2fca2dfabc5e", consulInfo.Host, consulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 轮询访问
	)
	if err != nil {
		zap.S().Fatalf("[goods-web] 连接 【商品服务】 失败")
	}
	global.GoodsSrvClient = proto.NewGoodsClient(goodsConn)
}
